package com.fingerth.myjsondemo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fingerth.myjsondemo.UserRepository;
import com.fingerth.myjsondemo.tab.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("test")
public class HelloWorldController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("hello")
    public String sayHello() {
        User usb = new User("张三", 16, "很懒,没留下什么......");
        userRepository.save(usb);
        try {
            //User usb = userRepository.findById(1).get();
            //return  new ObjectMapper().writeValueAsString(new UserBean("fingerth", 26, "很懒,没留下什么......"));
            return new ObjectMapper().writeValueAsString(usb);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "Hello World";
        }
    }


    @GetMapping("hello1")
    public String sayHello1(Long id) {
        Optional<User> opt = userRepository.findById(id);
        if (opt.isPresent()) {
            User usb = opt.get();
            try {
                return new ObjectMapper().writeValueAsString(usb);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "Hello World";
    }


    @GetMapping("hello2")
    public String sayHello2() {
        Optional<User> opt = userRepository.findById(2L);
        return getString(opt);
    }

    @PostMapping("postpic")
    public String postPicture(Long id) {
        Optional<User> opt = userRepository.findById(id);
        return getString(opt);
    }


    private String getString(Optional<User> opt) {
        if (opt.isPresent()) {
            User usb = opt.get();
            try {
                return new ObjectMapper().writeValueAsString(usb);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "Hello World";
    }

}
